<template>
  <div>
    <SearchForm @search="getTableData" @reset="clearSearchForm" :is-search-disabled="isSearchDisabled">
      <el-col :span="8">
        <el-form-item :label="$t('用户姓名')">
          <el-input v-model="page.name"/>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item :label="$t('手机号码')">
          <el-input v-model="page.phone"/>
        </el-form-item>
      </el-col>
      <!--      <el-col :span="8" :xs="24">-->
      <!--        <el-form-item :label="$t('身份证号码')" prop="phone" label-width="100px">-->
      <!--          <el-input v-model="page.idCard" clearable/>-->
      <!--        </el-form-item>-->
      <!--      </el-col>-->
      <el-col :span="8" v-show="$permiss[931]">
        <el-form-item :label="$t('营销APP')">
          <el-select style="width: 100%" v-model="page.productName" clearable>
            <el-option v-for="item in marketingProduct" :key="item.productId" :label="item.appName"
                       :value="item.productName"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <!--      <el-col :span="8">-->
      <!--        <el-form-item :label="$t('营销状态')">-->
      <!--          <el-select style="width: 100%" v-model="page.marketingStatus" clearable>-->
      <!--            <el-option v-for="item in marketingStatus" :key="item.value" :label="item.label"-->
      <!--                       :value="item.value"></el-option>-->
      <!--          </el-select>-->
      <!--        </el-form-item>-->
      <!--      </el-col>-->
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('跟进次数')">
          <el-input v-model.number="page.followUpNum" class="input-with-select">
            <el-select style="width: 60px" v-model="page.followUpNumOperation"
                       slot="prepend">
              <el-option v-for="item in symbolList" :key="item.label" :label="item.label"
                         :value="item.label"></el-option>
            </el-select>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24" v-show="$permiss[951]">
        <el-form-item :label="$t('营销结果')">
          <el-cascader
              style="width: 100%"
              v-model="page.causeKey"
              :options="selectCause"
              :props="{ checkStrictly: true,value:'key',label:'value' }"
              clearable></el-cascader>
        </el-form-item>
      </el-col>
      <!--      <el-col :span="12">-->
      <!--        <el-form-item :label="$t('最后结清时间')" label-width="100px">-->
      <!--          <el-date-picker-->
      <!--              v-model="page.settleTimeValue"-->
      <!--              style="width: 100%"-->
      <!--              unlink-panels-->
      <!--              value-format="yyyy-MM-dd"-->
      <!--              type="daterange"-->
      <!--              range-separator="~"-->
      <!--              :start-placeholder="$t('开始时间')"-->
      <!--              :end-placeholder="$t('结束时间')">-->
      <!--          </el-date-picker>-->
      <!--        </el-form-item>-->
      <!--      </el-col>-->
      <el-col :span="10">
        <el-form-item :label="$t('分单时间')">
          <el-date-picker
              v-model="page.distributionTimeValue"
              style="width: 100%"
              unlink-panels
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="~"
              :start-placeholder="$t('开始时间')"
              :end-placeholder="$t('结束时间')">
          </el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="10">
        <el-form-item :label="$t('跟进时间')">
          <el-date-picker
              v-model="page.followTimeValue"
              style="width: 100%"
              unlink-panels
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="~"
              :start-placeholder="$t('开始时间')"
              :end-placeholder="$t('结束时间')">
          </el-date-picker>
        </el-form-item>
      </el-col>
    </SearchForm>
    <el-card shadow="never" style="margin-top: 10px">
      <Table style="margin-top: 10px" :table-column="tableColumn" @handleSizeChange="handleSizeChange"
             @handleCurrentChange="handleCurrentChange" :table-data="tableData" :page="page">
        <template slot="status" slot-scope="{row}">
          {{ marketingStatus.filter(v => v.value === parseInt(row.marketingStatus))[0].label }}
        </template>
        <template slot="phone" slot-scope="{row}">
          <el-popover
              placement="right"
              width="120px"
              trigger="click">
            <SelectCallPhone :phone="row.phone" modeType="4" :marketingType="3" :marketingRows="row"/>
            <el-link slot="reference"  :underline="false" type="primary">{{
                row.phone
              }}
            </el-link>
          </el-popover>
        </template>
        <template slot="result" slot-scope="{row}">
          <div v-if="row.cause1 && row.cause1">
            {{ row.cause1 + '-' + row.cause2 }}
          </div>
        </template>
        <template slot="isBlack" slot-scope="{row}">
          {{ row.isBlackList === 0 ? $t('否') : row.isBlackList === 1 ? $t('是') : '' }}
        </template>
        <template slot="handle" slot-scope="{row}">
          <el-button type="text" @click="remark(row)" v-show="$permiss[934]">{{ $t('备注') }}</el-button>
          <el-button v-show="$permiss[938]" type="text" @click="lookRemark(row)">{{ $t('备注详情') }}</el-button>
        </template>
      </Table>
    </el-card>
    <!--    备注-->
    <Dialog :visible.sync="visibleRecord" :title="$t('备注')" :footer="false" @cancel="visibleRemark = false"
            @close="recordPage.timeValue = null" width="50%">
      <el-row :gutter="24" style="margin: 0">
        <el-form label-width="80px">
          <el-col :span="14">
            <el-form-item :label="$t('跟进时间')">
              <el-date-picker
                  v-model="recordPage.timeValue"
                  style="width: 100%"
                  unlink-panels
                  value-format="yyyy-MM-dd"
                  type="daterange"
                  range-separator="~"
                  :start-placeholder="$t('开始时间')"
                  :end-placeholder="$t('结束时间')">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="10" style="text-align: right">
            <el-button type="primary" @click="lookRemark(tableRows)">{{ $t('查询') }}</el-button>
            <el-button @click="recordPage.timeValue = [],lookRemark(tableRows)">{{ $t('重置') }}</el-button>
          </el-col>
        </el-form>
      </el-row>
      <Table :table-column="recordColumn" @handleSizeChange="(val) => {
        recordPage.pageSize= val
        lookRemark(tableRows)
      }"
             @handleCurrentChange="(val) => {
        recordPage.pageNum= val
        lookRemark(tableRows)
      }" :table-data="recordData" :loading="loading" :page="recordPage">
        <template slot="result" slot-scope="{row}">
          <div v-if="row.cause1 && row.cause1">
            {{ row.cause1 + '-' + row.cause2 }}
          </div>
        </template>
      </Table>
    </Dialog>
    <!--    添加备注-->
    <Dialog :visible.sync="visibleRemark" :title="$t('营销记录')" @close="clearRemark"
            @confirm="remarkConfirm" @cancel="visibleRemark = false"
    >
      <el-form label-width="80px" :model="remarkForm" ref="remarkForm">
        <el-form-item :label="$t('营销结果')" prop="cause1" :rules="[
          {required: true, message: this.$t('不能为空')},
        ]">
          <el-select v-model="remarkForm.cause1" @change="causeChange">
            <el-option v-for="item in marketingCause" v-if="item.code === 0" :key="item.key" :label="item.value"
                       :value="item.key"></el-option>
          </el-select>
          <div style="margin-top: 10px" v-if="marketingTags.length !== 0">
            <el-tag v-for="item in marketingTags" :effect="item.key === remarkForm.cause2 ? 'dark' : 'plain'"
                    :key="item.key"
                    @click="tagsClick(item)" :label="item.key" style="margin: 0 10px 10px 0;cursor: pointer">
              {{ item.value }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item :label="$t('备注')">
          <el-input type="textarea" v-model="remarkForm.remark" :rows="4"></el-input>
        </el-form-item>
      </el-form>
    </Dialog>
  </div>
</template>

<script>
import {selectProduct} from "@/api/system";
import {
  fetchMarketingCause,
  reBorrowBacklogList,
  reBorrowRemarkList,
  reBorrowInsertRemark,
  marketingCallPhone
} from "@/api/marketing";
import {dateFormatSection} from "@/utils/tools";

export default {
  name: "againUserMarketAgency",

  data() {
    return {
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        followUpNumOperation: '≧'
      },
      marketPersonnel: [],
      marketingProduct: [],
      resourcesProduct: [],
      symbolList: [
        {label: '>'},
        {label: '='},
        {label: '≧'},
        {label: '≦'},
        {label: '<'}
      ],
      marketingStatus: [
        {label: this.$t('待跟进'), value: 1},
        {label: this.$t('跟进中'), value: 2},
        {label: this.$t('已申请'), value: 3},
      ],
      tableColumn: [
        {label: this.$t('用户姓名'), prop: 'name', minWidth: 100},
        {label: this.$t('手机号码'), slot: 'phone', minWidth: 100},
        {label: this.$t('邮箱'), prop: 'eMali', minWidth: 100},
        {label: 'whatsAPP', prop: 'whatsApp', minWidth: 100},
        {label: 'zalo', prop: 'zalo', minWidth: 100},
        // {label: this.$t('身份证号码'), prop: 'idCard', minWidth: 100},
        {label: this.$t('是否黑名单'), slot: 'isBlack', minWidth: 100},
        {label: this.$t('性别'), prop: 'gender', minWidth: 100},
        {label: this.$t('年龄'), prop: 'age', minWidth: 100},
        // {label: this.$t('最后结清时间'), prop: 'settleTime', minWidth: 150},
        // {label: this.$t('最后结清金额'), prop: 'settleAmount', minWidth: 100},
        // {label: this.$t('累计结清笔数'), prop: 'settleNum', minWidth: 100},
        {label: this.$t('分单时间'), prop: 'singleTime', minWidth: 150},
        {label: this.$t('营销APP'), prop: 'appName', minWidth: 100},
        {label: this.$t('营销状态'), prop: 'loanStatus', slot: 'status', minWidth: 100},
        {label: this.$t('跟进次数'), prop: 'followUpNum', minWidth: 100},
        {label: this.$t('跟进时间'), prop: 'followUpTime', minWidth: 150},
        {label: this.$t('营销结果'), slot: 'result', minWidth: 150},
        {
          label: this.$t('操作'),
          minWidth: 150,
          slot: 'handle',
          fixed: 'right',
          isHide: !this.$permiss[933]
        },
      ],
      tableData: [],
      visibleTransfer: false,
      visibleRemark: false,
      visibleRecord: false,
      recordColumn: [
        {label: this.$t('跟进时间'), prop: 'followUpTime', minWidth: 150},
        {label: this.$t('营销结果'), slot: 'result', minWidth: 100},
        {label: this.$t('备注'), prop: 'remark', minWidth: 200},
        {label: this.$t('处理人'), prop: 'inputName', minWidth: 100},
      ],
      recordData: [],
      recordPage: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      remarkForm: {},
      tableRows: {},
      marketingCause: [],
      marketingTags: [],
      selectCause: [],
      isSearchDisabled: false,
      loading: false,
      callPhoneNumber: null
    }
  },
  mounted() {
    this.getSelect()
    this.getTableData()
  },
  methods: {
    async getTableData() {
      this.isSearchDisabled = true
      const [settleTimeStart, settleTimeEnd] = dateFormatSection(this.page.settleTimeValue || [])
      const [singleTimeStart, singleTimeEnd] = dateFormatSection(this.page.distributionTimeValue || [])
      const [followUpTimeStart, followUpTimeEnd] = dateFormatSection(this.page.followTimeValue || [])
      const [cause1, cause2] = this.page.causeKey || []
      const params = {
        ...this.page,
        settleTimeStart, settleTimeEnd, singleTimeStart, singleTimeEnd,
        followUpTimeStart, followUpTimeEnd,
        followUpNumOperation: this.page.followUpNumOperation === '≧' ? '>=' : this.page.followUpNumOperation === '≦' ? '<=' : this.page.followUpNumOperation,
        cause1,
        cause2
      }
      delete params.settleTimeValue
      delete params.distributionTimeValue
      delete params.followTimeValue
      delete params.causeKey
      this.loading = true
      const res = await reBorrowBacklogList(params)
      if (res.code === 1) {
        const {list, total} = res.data
        this.tableData = list.map(item => {
          item.loanStatus = item.loanStatus === 1 ? this.$t('未申请') : item.loanStatus === 2 ? this.$t('已申请') : ''
          item.gender = parseInt(item.gender) === 1 ? this.$t('男') : parseInt(item.gender) === 0 ? this.$t('女') : ''
          return item
        })
        this.page = {
          ...this.page,
          total
        }
        this.isSearchDisabled = false
        this.loading = false
      } else {
        this.isSearchDisabled = false
        this.loading = false
      }
    },
    // 打电话
    async callPhone({userId}) {
      const res = await marketingCallPhone({userId: userId})
      if (res.code === 1) {
        this.callPhoneNumber = res.data.phone
      }
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      this.getTableData()
    },
    handleCurrentChange(val) {
      this.page.pageNum = val
      this.getTableData()
    },
    clearSearchForm() {
      this.page = {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        followUpNumOperation: '≧'
      }
      this.getTableData()
    },
    // 查看营销备注
    async lookRemark(row) {
      const [followTimeStart, followTimeEnd] = dateFormatSection(this.recordPage.timeValue || [])
      const params = {
        ...this.recordPage,
        followTimeStart, followTimeEnd,
        reBorrowId: row.id
      }
      delete params.timeValue
      this.tableRows = {...row}
      const res = await reBorrowRemarkList(params)
      if (res.code === 1) {
        const {list, pageNum, pageSize, total} = res.data
        this.visibleRecord = true
        this.recordData = list
        this.recordPage = {
          ...this.recordPage,
          pageNum, pageSize, total
        }
      }
    },
    //清空备注表单
    clearRemark() {
      this.remarkForm = {}
      this.marketingTags = []
      this.$refs.remarkForm.resetFields()
    },
    async remark(row) {
      const {id} = row
      this.remarkForm = {id}
      this.visibleRemark = true
    },
    causeChange(key) {
      const list = this.marketingCause.filter(i => i.key === key)
      // 过滤标签列表
      const tageList = list.length ? this.marketingCause.filter(i => i.type === list[0].type && i.code !== 0) : []
      if (tageList.length) this.remarkForm.cause2 = tageList[0].key
      this.marketingTags = tageList
    },
    tagsClick({key}) {
      this.remarkForm = {
        ...this.remarkForm,
        cause2: key
      }
    },
    // 提交备注
    remarkConfirm() {
      this.$refs.remarkForm.validate(async v => {
        if (v) {
          const {remark, id, cause1, cause2} = this.remarkForm
          const res = await reBorrowInsertRemark({
            cause1, cause2,
            remark,
            reBorrowUserId: id
          })
          if (res.code === 1) {
            this.$message.success(this.$t('新增成功'))
            this.visibleRemark = false
            this.getTableData()
          }
        }
      })
    },
    async getSelect() {
      selectProduct({
        type: 4
      }).then(res => {
        this.marketingProduct = res.data
      })
      fetchMarketingCause().then(res => {
        this.marketingCause = res.data
        const marketingCause = this.marketingCause.filter(item => {
          if (item.code === 0) {
            const children = this.marketingCause.filter(child => child.type === item.type && child.code !== 0)
            if (children.length > 0) item.children = children
            return item.code === 0
          }
        })
        this.selectCause = marketingCause
      })
    }
  }
}
</script>

<style scoped>

</style>
